package com.hbnu.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 需求：数据库增、删、改操作
 *
 * @author kittychen
 * @since 2025-10-21 14:40
 */
public class JdbcDemo01 {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        try {
            // 1.注册驱动
            // DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2.获取数据库连接
            String url = "jdbc:mysql://localhost:3306/class2310?serverTimezone=GMT&useSSL=false&characterEncoding=utf-8";
            String user = "root";
            String password = "123456";
            connection = DriverManager.getConnection(url, user, password);
            // System.out.println("数据库连接对象：" + connection);

            // 3、获取数据库操作对象
            statement = connection.createStatement();

            // 4、执行SQL语句
            String sql = "insert into tb_user values(1, 'zhangsan','123456',45632.25)";
            // String sql = "update tb_user set username='lisi' where id=1";
            // String sql = "delete from tb_user where id=1";
            int row = statement.executeUpdate(sql);
            System.out.println("受影响的行数：" + row);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6、关闭资源
            try {
                if (statement != null) {
                    statement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
